package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

public class MyFilter implements GlobalFilter {
    private static List<String> paths = new ArrayList<>();
    static {
        paths.add("/login/in");
        paths.add("/v2/api-docs");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        for (String p : paths) {
            if (p.contains(path)){
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            return response.setComplete();
        }
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i<1){
                String id = claimsBody.getId();
                ServerHttpRequest httpRequest = request.mutate().header("userId", id).build();
                exchange.mutate().request(httpRequest).build();
                return chain.filter(exchange);
            }
            return response.setComplete();
        } catch (Exception e) {
            e.printStackTrace();
            return response.setComplete();
        }

    }
}
